#pragma once
#include "nocopy.hpp"
#include <string>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "InetAddr.hpp"
#include <strings.h>
static const std::string defaultip = "127.0.0.1";
static const uint16_t defaultport = 8888;
static const int defaultsockfd = -1;
class UdpServer : public nocopy
{
public:
    UdpServer(uint16_t port = defaultport)
    : _port(port), _sockfd(defaultsockfd)
    {}

    void Init()
    {
        //int _sockfd = socket(AF_INET, SOCK_DGRAM, 0); //我靠多了个int
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0); //我靠多了个int
        if(_sockfd < 0)
        {
            exit(1);
        }

        lg.LogMessage(Debug, "socker create success\n");

        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof local);
        if(n < 0) 
        {
            exit(2);
        }
        lg.LogMessage(Debug, "socker bind success\n");

    }
    void Start()
    {
        char buffer[1024];
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof peer;
            int n = recvfrom(_sockfd, buffer, sizeof buffer - 1, 0, (struct sockaddr*)&peer, &len);
            if(n > 0)
            {
                lg.LogMessage(Debug, "recvfrom success\n");
                InetAddr addr(peer);
                buffer[n] = 0;
                sendto(_sockfd, buffer, sizeof buffer, 0, (struct sockaddr*)&peer, len);
                std::cout << "[" << addr.PrintDebug() << "]# " << buffer << std::endl;
                lg.LogMessage(Debug, "sendto success\n");

            }
        }
    }
    ~UdpServer()
    {}
private:
    // std::string _ip;
    uint16_t _port;
    int _sockfd;
};